//
//  ExplorationViewController.m
//  TestApplication
//
//  Created by Hanlingyu on 16/8/29.
//  Copyright © 2016年 ltq. All rights reserved.
//

#import "ExplorationViewController.h"
#import "TAMacro.h"
#import "ExplorationCycleImageTableViewCell.h"
#import "AFNetworking.h"
#import "BaseModel.h"
#import "Banner.h"
#import "Channel.h"
#import "Content.h"
#import "ExplorationModel.h"
#import "Hotcomments.h"
#import "Img.h"
#import "Posts.h"
#import "Recommend.h"
#import "NoTitleHotRecommendTableViewCell.h"
#import "HaveTitleHotRecommendTableViewCell.h"

#import "ExplorationListContent.h"
#import "ExplorationListJoin.h"
#import "ExplorationListModel.h"
#import "ExplorationListTableViewCell.h"
#import "NotitleExplorationListTableViewCell.h"
#import "HaveTitleExplorationListTableViewCell.h"
#import "ChannelsDetailViewController.h"
#import "MJRefresh.h"
#import "PostsDetailViewController.h"
#import "PostVoiceViewController.h"

@interface ExplorationViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    backCellHeight
>

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UITableView *explorationTableView;
@property (nonatomic, strong) ExplorationModel *explorationModel;
@property (nonatomic, strong) ExplorationListModel *explorationListModel;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) CGFloat cellHeight;

@end

@implementation ExplorationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataArray = [NSMutableArray array];
    self.view.backgroundColor = [UIColor colorWithWhite:0.917 alpha:1];
    self.page = 0;

    [self createNavigationBar];
    [self handleData];
//    [self handleSecData];
    [self createTableView];
    
    
    // 下拉刷新
    [self refreshNew];
    // 上拉加载
    [self refreshMore];
    

    

}

- (void)refreshNew {
    self.explorationTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self handleData];
    }];
    // 马上进入刷新状态
    [self.explorationTableView.mj_header beginRefreshing];
}


- (void)refreshMore {
    
        self.explorationTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            if (_page <= 40) {
                [self handleSecData];
            } else {
                [self endRefresh];
            }
        }];
}

- (void)endRefresh {
    [self.explorationTableView.mj_header endRefreshing];
    [self.explorationTableView.mj_footer endRefreshing];
}




- (void)heigthOfCell:(CGFloat)height {
    
    self.cellHeight = height;
//    NSLog(@"%lf", height);
}
// 第一次网络请求:
- (void)handleData {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    NSString *parmeters = @"c=Search&m=getList&p=%7B%22uid%22%3A%2257c01d33a9a36d0621c123f7%22%7D&t=t&v=v105";
    
    // 确定 parameter 字符串中含有:/?#[]@!$&’()*+,;=这些字符时候，这些字符需要被转化，以免与语法冲突
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    // 设置请求参数的字符串, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        self.page = 0;
         self.explorationModel = [ExplorationModel modelWithDic:responseObject];
        [_explorationTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}

// 第二次网络请求:
- (void)handleSecData {
    NSString *userid = @"57c01d33a9a36d0621c123f7";

    NSLog(@"%ld", _page);
    NSString *text = [NSString stringWithFormat:@"{\"uid\":\"%@\",\"createdAt\":%ld}", userid, _page];
    NSString *utf8Text = [text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    NSString *parmeters = [NSString stringWithFormat:@"c=Search&m=getRecommendList&p=%@&t=t&v=v105", utf8Text];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    NSString *postURLString = @"http://api.zheli.io:9501/";
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parmeters;
    }];
    // 正常post发送
    [manager POST:postURLString parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@", responseObject);
        [self endRefresh];
        if (_page == 0) {
            self.page += 10;
            self.explorationListModel = [ExplorationListModel modelWithDic:responseObject];
            [_explorationTableView reloadData];

        } else {
            self.page += 10;
            for (NSDictionary *dic in responseObject[@"content"]) {
                ExplorationListContent *listContent = [ExplorationListContent modelWithDic:dic];
                [self.explorationListModel.content addObject:listContent];
                [_explorationTableView reloadData];
                
            }
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
}

- (void)createTableView {
    
    self.explorationTableView = [[UITableView alloc] initWithFrame: CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 64) style:UITableViewStylePlain];
    _explorationTableView.backgroundColor = [UIColor whiteColor];
    _explorationTableView.delegate = self;
    _explorationTableView.dataSource = self;
    [self.view addSubview:_explorationTableView];
    _explorationTableView.separatorStyle = NO;

    
    [_explorationTableView registerClass:[ExplorationCycleImageTableViewCell class] forCellReuseIdentifier:@"cycleImageCellReuse"];
    [_explorationTableView registerClass:[NoTitleHotRecommendTableViewCell class] forCellReuseIdentifier:@"noTitleHotRecommendTableViewCellReuse"];
    [_explorationTableView registerClass:[HaveTitleHotRecommendTableViewCell class] forCellReuseIdentifier:@"haveTitleHotRecommendTableViewCellReuse"];
    [_explorationTableView registerClass:[NotitleExplorationListTableViewCell class] forCellReuseIdentifier:@"notitleExplorationListTableViewCellReuse"];
    [_explorationTableView registerClass:[HaveTitleExplorationListTableViewCell class] forCellReuseIdentifier:@"haveTitleExplorationListTableViewCellReuse"];

}


- (CGFloat)handleHeight:(Recommend *)recommend {
    Img *firstImg = recommend.posts[0].img.firstObject;
    Img *secImg = recommend.posts[1].img.firstObject;
    Img *thirdImg = recommend.posts[2].img.firstObject;
    Img *fourthImg = recommend.posts[3].img.firstObject;
    Img *fifthImg = recommend.posts[4].img.firstObject;
    Img *sixthImg = recommend.posts[5].img.firstObject;
    CGFloat temp = firstImg.w / firstImg.h + secImg.w / secImg.h + thirdImg.w / thirdImg.h;
    CGFloat heightOfFirstLine = (SCREEN_WIDTH - 44) / temp;
    CGFloat temp2 = fourthImg.w / fourthImg.h + fifthImg.w / fifthImg.h + sixthImg.w / sixthImg.h;
    CGFloat heightOfSecLine = (SCREEN_WIDTH - 44) / temp2;
    
    return heightOfSecLine + heightOfFirstLine + 120;
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 0) {
        if (_explorationModel.content.banner) {
            return 200;
        }
        return 0;
    } else if (indexPath.section == 1){
        Recommend *recommend = _explorationModel.content.recommend[indexPath.row];
        CGFloat cellHeight = [self handleHeight:recommend];

        return cellHeight;
    } else  {
        if (_explorationListModel.content[indexPath.row].title) {
            return 110;
        }
        return 80;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (_explorationModel.content.banner) {
            return 1;
        }
        return 0;
    } else if (section == 1){
        return _explorationModel.content.recommend.count;
    } else  {
        if (_explorationListModel.content) {
            return _explorationListModel.content.count;
        }
        return 0;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ExplorationCycleImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cycleImageCellReuse"];
        cell.bannerArray = _explorationModel.content.banner;
        return cell;
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            HaveTitleHotRecommendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"haveTitleHotRecommendTableViewCellReuse"];
            cell.recommend = _explorationModel.content.recommend[indexPath.row];
            
            __weak typeof(self) weakSelf = self;
            PostsDetailViewController *postDetailVC = [[PostsDetailViewController alloc] init];
            
            cell.postChannelDetailPage = ^(NSString *ID){
                
                [weakSelf.navigationController pushViewController:postDetailVC animated:YES];
                postDetailVC.postId = ID;
            };
            return cell;
        } else {
            NoTitleHotRecommendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noTitleHotRecommendTableViewCellReuse"];
            cell.recommend = _explorationModel.content.recommend[indexPath.row];
            __weak typeof(self) weakSelf = self;
            PostsDetailViewController *postDetailVC = [[PostsDetailViewController alloc] init];
            
            cell.postChannelDetailPage = ^(NSString *ID){
                
                [weakSelf.navigationController pushViewController:postDetailVC animated:YES];
                postDetailVC.postId = ID;
            };
            return cell;
        }
    } else  {
        ExplorationListContent *listContentModel = _explorationListModel.content[indexPath.row];
        if (listContentModel.title) {
            HaveTitleExplorationListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"haveTitleExplorationListTableViewCellReuse"];
            cell.listContent = listContentModel;
            return cell;
        } else {
            NotitleExplorationListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"notitleExplorationListTableViewCellReuse"];
            cell.listContent = listContentModel;
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSLog(@"第一分区");
    } else if (indexPath.section == 1) {
        ChannelsDetailViewController *channelVC = [[ChannelsDetailViewController alloc] init];
        channelVC.channelID = _explorationModel.content.recommend[indexPath.row].ID;
//        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:channelVC animated:YES];
        
    } else if(indexPath.section == 2){
                
        ChannelsDetailViewController *channelDetailVC = [[ChannelsDetailViewController alloc] init];
        channelDetailVC.channelID = _explorationListModel.content[indexPath.row].ID;
        [self.navigationController pushViewController:channelDetailVC animated:YES];
    }
}

- (void)createNavigationBar {
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    _titleLabel.center = CGPointMake(SCREEN_WIDTH / 2, 42);
    _titleLabel.textAlignment = 1;
    _titleLabel.textColor = [UIColor whiteColor];
    [self.backView addSubview:_titleLabel];
    _titleLabel.text = @"探索";}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
